const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const db = require('../db'); // 引入数据库连接

// 获取所有待处理的报修请求
router.get('/worker/repairs', (req, res) => {
    const token = req.headers['authorization'];

    if (!token) {
        return res.status(403).json({ message: "没有提供认证信息" });
    }
    // 多表关联查询
    const repairSql = `SELECT 
    r.repairId AS "维修ID",
    s.studentId AS "学号",
    s.name AS "学生姓名",
    d.building AS "楼栋",
    d.roomNumber AS "房间号",
    r.description AS "维修描述",
    r.status AS "维修状态",
    r.createdAt AS "提交时间"
FROM 
    repair_requests r
JOIN 
    students s ON r.studentId = s.studentId
JOIN 
    dormitories d ON s.dormitoryId = d.dormitoryId
ORDER BY 
    r.createdAt DESC;
`
    console.log(repairSql);
    // 验证token并获取工作人员身份（这里假设工作人员已登录并有相应权限）
    jwt.verify(token, "kio", (err, decoded) => {
        if (err) {
            return res.status(401).json({ message: "认证失败" });
        }

        // 获取未处理和处理中状态的报修记录
        const sql = 'SELECT * FROM repairs WHERE status IN ("未处理", "处理中") ORDER BY createdAt DESC';
        db.query(sql, (err, results) => {
            if (err) {
                return res.status(500).json({ message: "数据库查询失败" });
            }
            res.json(results);
        });
    });
});

// 更新报修状态
router.put('/worker/repair/:id', (req, res) => {
    const { id } = req.params;
    const { status } = req.body;  // 新的报修状态

    if (!['未处理', '处理中', '已解决'].includes(status)) {
        return res.status(400).json({ message: '无效的状态' });
    }

    const sql = 'UPDATE repairs SET status = ? WHERE id = ?';
    db.query(sql, [status, id], (err, results) => {
        if (err) {
            return res.status(500).json({ message: '更新报修状态失败' });
        }
        res.json({ message: '报修状态更新成功' });
    });
});

module.exports = router;
